<script setup>
import GoBackAndSearchNav from "@/components/GoBackAndSearchNav.vue";
import {ref} from 'vue'
import {useRouter} from 'vue-router'
import useSearchHistoryStore from "@/store/modules/SearchHistoryStore.js";
import {SEARCH_LIST_ROUTE} from "@/router/routes/search/SearchList.js";
import {elErrorMessageTip} from "@/utils/MessageTipUtils.js";
import {showConfirmDialog} from 'vant';
import 'vant/es/dialog/style'

const router = useRouter()
const searchHistoryStore = useSearchHistoryStore()

const keyWord = ref('')

const onSearch = () => {
  // 未输入搜索关键词
  if (keyWord.value.length <= 0) {
    elErrorMessageTip('请输入搜索关键词')
    return
  }
  // 保存搜索历史
  searchHistoryStore.saveKeyWord(keyWord.value)
  // 页面跳转，前往搜索结果页面
  router.push({name: SEARCH_LIST_ROUTE, query:{kw: keyWord.value}})
}

const searchByHistory = (kw) => {
  // 页面跳转，跳转到与搜索关键词对应的书籍商品搜索结果页面
  router.push({name: SEARCH_LIST_ROUTE, query:{kw}})
}

const clearSearchHistory = () => {
  showConfirmDialog({
    message: '是否确认清除搜索记录'
  }).then(() => {
    // on confirm
    searchHistoryStore.clearSearchHistory()
  }).catch(() => {
    // on cancel
  });
}
</script>

<template>
  <div class="search">
    <GoBackAndSearchNav :title="'搜索'" :placeholder="true"></GoBackAndSearchNav>
    <van-search
        v-model="keyWord"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        show-action
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div>
      <div class="p-2 flex justify-between text-gray-400">
        <span class="text-md">搜索历史</span>
        <van-icon @click="clearSearchHistory" name="delete-o" />
      </div>
      <div>
        <el-tag @click="searchByHistory(kw)" class="ml-2" v-for="kw in searchHistoryStore.searchHistory" type="info">{{ kw }}</el-tag>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">

</style>